package com.itheima.health.service.impl;

import com.itheima.health.common.MessageConst;
import com.itheima.health.dao.OrderDao;
import com.itheima.health.dao.OrderSettingDao;
import com.itheima.health.exception.BusinessRuntimeException;
import com.itheima.health.pojo.Member;
import com.itheima.health.pojo.Order;
import com.itheima.health.pojo.OrderSetting;
import com.itheima.health.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;

@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderDao orderDao;
    @Autowired
    private OrderSettingDao orderSettingDao;

    @Override
    public Order findById(Integer id) {
        return orderDao.selectById(id);
    }

    @Override
    public Integer[] findSetmealId() {
        return orderDao.selectSetmealId();
    }

    @Override
    public Integer findCount(Integer setmealId) {
        return orderDao.selectCount(setmealId);
    }

    @Override
    public Integer addOrder(Order order) {
        Date orderDate = order.getOrderDate();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String date=simpleDateFormat.format(orderDate);
        OrderSetting orderSetting = orderSettingDao.selectOrderSettingByOrderDate(date);
        if (orderSetting==null) {
            throw new BusinessRuntimeException(MessageConst.SELECTED_DATE_CANNOT_ORDER);
        } else if (orderSetting.getReservations()>=orderSetting.getNumber()) {
            throw new BusinessRuntimeException(MessageConst.ORDER_FULL);
        }
        //查询是不是同一个人同一天同一个套餐，就是查询套餐表
        Order dbOrder = orderDao.selectOrderByMemberIdOrderDateSetmealId(order.getMemberId(), date, order.getSetmealId());
        if (dbOrder!=null) {
            throw new BusinessRuntimeException(MessageConst.HAS_ORDERED);
        }
        Integer count = orderDao.insertOrder(order);

        orderSettingDao.updateReservationsById(orderSetting.getId(),orderSetting.getReservations()+1);

        return count;

    }




}
